package com.heima.article.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.config.ApArticleConfig;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.article.vos.UserInteractionVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章服务实现类
 */
@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    //注入mapper
    private final ApArticleMapper articleMapper;

    private final ApArticleConfigMapper articleConfigMapper;

    private final ApArticleContentMapper articleContentMapper;

    //freemarker
    private final ArticleFreemarkerSreviceImpl articleFreemarkerSrevice;

    //rabbittemplate
    private final RabbitTemplate rabbitTemplate;

    //redis
    private final CacheService cacheService;

    private static final Integer MAX_PAGE_SIZE=50;

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type 1.加载更多   2。 加载最新
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //1.检验参数

        //1.1 分页条件的校验
        Integer size = dto.getSize();
        if (size == null|| size <= 0) {
            size=10;
        }

        //分页的值不超过50
        Math.min(size,MAX_PAGE_SIZE);

        //校验参数type
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !dto.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type=ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //频道参数校验
        if ((dto.getMaxBehotTime()==null)){
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }

        //2.查询
        List<ApArticle> apArticles = articleMapper.loadArticleList(dto, type);

        //3.返回
        return ResponseResult.okResult(apArticles);
    }


    /**
     * 保存App端相关文章
     *
     * @param apArticleDto
     * @return
     */

    @Override
    public ResponseResult saveArticle(ApArticleDto apArticleDto) {

    /*    //服务降级测试
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        //1.检查参数
        if (apArticleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(apArticleDto, apArticle);


        //2.判断是否存在id
        if (apArticleDto.getId() == null) {
            //2.1不存在id 保存  文章  文章配置 文章内容

            //1.保存文章
            save(apArticle);

            //2.保存配置
            ApArticleConfig aapArticleConfig = new ApArticleConfig(apArticle.getId());
            articleConfigMapper.insert(aapArticleConfig);

            //3.保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(apArticleDto.getContent());
            articleContentMapper.insert(apArticleContent);

        }else {
            // 2.2 存在id 修改    文章  文章内容

            //1.修改文章
            updateById(apArticle);

            //2.修改文章内容
            ApArticleContent apArticleContent = articleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(apArticleDto.getContent());
            articleContentMapper.updateById(apArticleContent);

        }


        //异步调用  将静态页面加载到minio中
        String path = articleFreemarkerSrevice.buildArticleToMinIo(apArticle, apArticleDto.getContent());

        //4.4 修改ap_article表，保存static_url字段
        update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,apArticle.getId())
                .set(ApArticle::getStaticUrl,path));


        //5.异步发送消息 创建es索引
        createArticleESIndex(apArticle,apArticleDto.getContent(),path);

        return ResponseResult.okResult(apArticle.getId());
    }


    /**
     * 加载数据回显
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        //0.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if(user != null){
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(likeBehaviorJson)){
                islike = true;
            }
            //不喜欢的行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(unLikeBehaviorJson)){
                isunlike = true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR+user.getId(),dto.getArticleId().toString());
            if(StringUtils.isNotBlank(collctionJson)){
                iscollection = true;
            }

            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            System.out.println(score);
            if(score != null){
                isfollow = true;
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }


    /**
     * 异步发送消息 创建es索引
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {

        SearchArticleVo vo=new SearchArticleVo();

        //设置vo属性
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        //发送消息
        rabbitTemplate.convertAndSend(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,vo);

    }


    /**
     * 加载文章
     *
     * @param dto
     * @param type      1.加载更多   2。 加载最新
     * @param firstPage true 是首页  false 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {

        //如果当前是首页
        if (firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                //将json转化为vo集合返回
                List<HotArticleVo> hotArticleVos = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVos);

                return responseResult;
            }
        }

        //如果当前不是首页
        return load(dto, type);
    }


}
















